package com.sciencep.pro.admin.system.controller;

import com.sciencep.pro.admin.system.service.LoginService;
import com.sciencep.pro.common.domain.ResponseResult;
import com.sciencep.pro.common.exception.CustomException;
import com.sciencep.pro.core.domain.entity.Account;
import com.sciencep.pro.core.service.RedisService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.sciencep.pro.common.config.Constant.USERINFO_CACHE_PREFIX;

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {



    @Autowired
    LoginService loginService;

    @Autowired
    RedisService redisService;

    @GetMapping("/getLoginUserInfo")
    public ResponseResult<Object> getLoginUserInfo(@RequestParam("userId") String userId) throws CustomException{


        return new ResponseResult<>().success(loginService.login(userId));
    }

    @GetMapping("/loginOut")
    public ResponseResult<Object> loginOut(@RequestParam("userId") String userId) throws CustomException {
        try {
            redisService.del(USERINFO_CACHE_PREFIX + userId);
        }catch (Exception e){
            throw new CustomException("redis连接失败,无法登出");
        }
        return new ResponseResult<>().success("登出成功");
    }

    @GetMapping("/getUserByCode")
    public ResponseResult<Object> getUserByCode(@RequestParam String code) throws ApiException, CustomException {
        return loginService.getUserByCode(code);
    }


    //前端测试连接本地的接口
    @GetMapping("/getUserByCode1")
    public ResponseResult<Object> getUserByCode1(@RequestParam String code) throws ApiException, CustomException {
        return loginService.getUserByCode1(code);
    }

    @PostMapping("/getAccount")
    public ResponseResult<Object> getAccount(@RequestBody Account account) throws CustomException {
        return loginService.getAccount(account);
    }


    @GetMapping("/accountOut")
    public ResponseResult<Object> accountOut(@RequestParam("accountNumber") String accountNumber) throws CustomException {
        try {
            redisService.del(USERINFO_CACHE_PREFIX + accountNumber);
        }catch (Exception e){
            throw new CustomException("redis连接失败,无法登出");
        }
        return new ResponseResult<>().success("登出成功");
    }



}
